package com.fauks.gmall.item.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.fauks.gmall.bean.PmsProductSaleAttr;
import com.fauks.gmall.bean.PmsSkuInfo;
import com.fauks.gmall.bean.PmsSkuSaleAttrValue;
import com.fauks.gmall.service.ProductService;
import com.fauks.gmall.service.SkuService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ItemController {

    @Reference
    private SkuService skuService;

    @Reference
    private ProductService productService;

    @RequestMapping("{skuId}.html")
    public String itemDetail(@PathVariable String skuId, Model model, HttpServletRequest request) {
        PmsSkuInfo skuInfo = skuService.getSkuById(skuId, request.getRemoteAddr());
        model.addAttribute("skuInfo", skuInfo);
        //获取商品所有销售属性列表
        List<PmsProductSaleAttr> productSaleAttrList = productService.spuSaleAttrListCheckBySku(skuInfo.getProductId(), skuInfo.getId());
        model.addAttribute("spuSaleAttrListCheckBySku", productSaleAttrList);

        //封装所有sku map
        Map<String, String> skuAttrMap = new HashMap<>();
        List<PmsSkuInfo> skuInfoList = skuService.getSkuSaleAttrMapBySpu(skuInfo.getProductId());
        for (PmsSkuInfo pmsSkuInfo : skuInfoList) {
            //sku id为值
            String v = pmsSkuInfo.getId();
            String k = "";
            List<PmsSkuSaleAttrValue> pmsSkuSaleAttrValueList = pmsSkuInfo.getPmsSkuSaleAttrValueList();
            for (PmsSkuSaleAttrValue pmsSkuSaleAttrValue : pmsSkuSaleAttrValueList) {
                k += pmsSkuSaleAttrValue.getSaleAttrValueId() + "|";
            }
            skuAttrMap.put(k, v);
        }
        String skuAttrMapStr = JSON.toJSONString(skuAttrMap);
        model.addAttribute("skuSaleAttrHashJsonStr", skuAttrMapStr);
        return "itemDetail";
    }

    @RequestMapping("test")
    public String test() {
        return "test";
    }
}
